//
// Created by Lenovo on 2023/10/2.
//
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 3e5+7;
string check(int x)
{
    string s;
    int f=0;
    while(x)
    {
        if(x&1)f=1;
        if(f)s+='0'+x&1;
        x>>=1;
    }
    return s;
}
void solve()
{
    int x,y;
    cin>>x>>y;
    int a=x,b=y;
    ll cnt=0;
    while(x%y!=0)
    {
        x%=y;
        if(check(x).size()<check(y).size())
        {
            cout<<"-1";
            return ;
        }
        cnt+=x;
        x*=2;
    }
    cout<<cnt;

}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        solve();
        cout<<endl;
    }
    return 0;
}